package com.sanq.product.books.splide;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.ChapterContentVo;
import com.sanq.product.books.entity.vo.ChapterVo;
import com.sanq.product.books.module.ServiceModule;
import com.sanq.product.books.redis.JedisPoolService;
import com.sanq.product.books.worker.Id;
import com.sanq.product.config.utils.string.MatcherUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * com.sanq.product.books.splide.SplideChapterService
 *
 * 爬取小说章节和内容
 * @author sanq.Yan
 * @date 2019/12/17
 */
@Component
public class SplideChapterService {

    @Resource
    private JedisPoolService jedisPoolService;
    @Value("${WORKER_ID}")
    private Integer workerId;
    @Value("${DATACENTER_ID}")
    private Integer datacenterId;

    public void saveChapter(ServiceModule serviceModule, Long booksId, String chapterName, String chapterUrl) throws IOException {

        //验证URL是否完整， 否则拼接URL
        if (!MatcherUtil.isUrl(chapterUrl))
            chapterUrl = serviceModule.getUrl().concat(chapterUrl);

        ChapterVo chapterVo = new ChapterVo();

        chapterVo.setBookId(booksId);

        Long chapterId =  Id.getInstance(workerId, datacenterId).getId();

        chapterVo.setId(chapterId);
        chapterVo.setChapterName(chapterName);

        chapterVo.setCostGold(new BigDecimal(0));
        chapterVo.setCreateTime(new Date());

        //判断当前章节是否已经存在
        String existsMember = String.format("%d:%s",booksId, chapterName);

        if (!jedisPoolService.zrank(Redis.RedisKey.EXISTS_CHAPTER, existsMember)) {
            //章节保存
            jedisPoolService.putList(Redis.RedisKey.SPLIDE_CHAPTER_LIST_KEY, JsonUtil.obj2Json(chapterVo));
            jedisPoolService.putSet(Redis.RedisKey.EXISTS_CHAPTER, chapterId, existsMember);

            //内容获取
            Document booksDetail = Jsoup.connect(chapterUrl).userAgent(serviceModule.getUserAgent()).get();
            String content = booksDetail.select(serviceModule.getContent()).html();

            ChapterContentVo chapterContentVo = new ChapterContentVo();
            chapterContentVo.setBookId(booksId);
            chapterContentVo.setChapterId(chapterId);
            chapterContentVo.setContent(content);

            //内容保存
            jedisPoolService.putList(Redis.RedisKey.SPLIDE_CHAPTER_CONTENT_LIST_KEY, JsonUtil.obj2Json(chapterContentVo));
        }

    }
}
